用httpclient编写的curl等效代码:java

发布于 2024-10-19 18:02:07 字数 3206 浏览 2 评论 0原文

有一个在 tomcat 中运行的 Web 应用程序,基于我的 Web 应用程序中的某些操作,我需要编写一个将触发 curl 的 java 代码(http://curl.haxx.se)。然后,Curl 将查询第三方应用程序并返回 XML/JSON。

我必须阅读此内容并向用户返回适当的响应。

我知道这可以通过curl来完成,但是使用命令行工具从Web应用程序发出请求并不是最好的方法,因此我用Java编写了一段代码,httpclient API。

curl代码是

curl -u username:password -d "param1=aaa& param2=bbb" -k http://www.testme.com/api/searches.xml

curl默认使用base64编码。因此,我编写的Java中的相应代码是

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;

public class NCS2
{

  public static void main(String args[]) {

    String username = "abc";
    String password = "xyz";

    HttpClient httpclient = new HttpClient();
    BufferedReader bufferedreader = null;


    PostMethod postmethod = new PostMethod("https://www.testabc.com/api/searches.xml");
    postmethod.addParameter("_def_id","8");
    postmethod.addParameter("dobday", "6");
    postmethod.addParameter("dobmonth","6");
    postmethod.addParameter("dobyear", "1960");
    postmethod.addParameter("firstname", "Test");
    postmethod.addParameter("lastname", "Test");


    String username_encoded = new String(Base64.encodeBase64(username.getBytes()));
    System.out.println("username_encoded ="+username_encoded);

    String password_encoded = new String(Base64.encodeBase64(password.getBytes()));
    System.out.println("password_encoded ="+password_encoded);

    httpclient.getState().setAuthenticationPreemptive(true);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials();
    credentials.setPassword(username_encoded);
    credentials.setUserName(password_encoded);

 httpclient.getState().setCredentials("FORM","http://www.testabc.com/api/searches.xml",credentials);   // I am not sure which one to use here..

    try{
          int rCode = httpclient.executeMethod(postmethod);
          System.out.println("rCode is" +rCode);

          if(rCode == HttpStatus.SC_NOT_IMPLEMENTED) 
           {
              System.err.println("The Post postmethod is not implemented by this URI");
               postmethod.getResponseBodyAsString();
           } 
             else if(rCode == HttpStatus.SC_NOT_ACCEPTABLE) {
                System.out.println(postmethod.getResponseBodyAsString());
          }
           else {
                      bufferedreader = new BufferedReader(new InputStreamReader(postmethod.getResponseBodyAsStream()));
                       String readLine;
        while(((readLine = bufferedreader.readLine()) != null)) {
          System.out.println("return value " +readLine);
      }
      }
    } catch (Exception e) {
      System.err.println(e);
    } finally {
      postmethod.releaseConnection();
      if(bufferedreader != null) try { bufferedreader.close(); } catch (Exception fe)    fe.printStackTrace();  }     }   }
}

使用它,我得到rCode的返回值为“406”。为什么我收到“不可接受”的回复任何可以帮助我更好地调试并解决此问题的内容。

have a web-application running in tomcat, based on certain actions in my web-applications I need to write a java code which would trigger curl (http://curl.haxx.se). Curl would then query a third-party application and return an XML/JSON.

This has to be read by me and return appropriate response to the user.

I know this can be done with curl but using a command line tool for making request from a web application is not the best way to go about it and thus I have written a code in Java, httpclient API.

The curl code was

curl -u username:password -d "param1=aaa& param2=bbb" -k http://www.testme.com/api/searches.xml

curl by default uses base64 encoding. Thus the corresponding code in Java which is written by me is

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;

public class NCS2
{

  public static void main(String args[]) {

    String username = "abc";
    String password = "xyz";

    HttpClient httpclient = new HttpClient();
    BufferedReader bufferedreader = null;


    PostMethod postmethod = new PostMethod("https://www.testabc.com/api/searches.xml");
    postmethod.addParameter("_def_id","8");
    postmethod.addParameter("dobday", "6");
    postmethod.addParameter("dobmonth","6");
    postmethod.addParameter("dobyear", "1960");
    postmethod.addParameter("firstname", "Test");
    postmethod.addParameter("lastname", "Test");


    String username_encoded = new String(Base64.encodeBase64(username.getBytes()));
    System.out.println("username_encoded ="+username_encoded);

    String password_encoded = new String(Base64.encodeBase64(password.getBytes()));
    System.out.println("password_encoded ="+password_encoded);

    httpclient.getState().setAuthenticationPreemptive(true);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials();
    credentials.setPassword(username_encoded);
    credentials.setUserName(password_encoded);

 httpclient.getState().setCredentials("FORM","http://www.testabc.com/api/searches.xml",credentials);   // I am not sure which one to use here..

    try{
          int rCode = httpclient.executeMethod(postmethod);
          System.out.println("rCode is" +rCode);

          if(rCode == HttpStatus.SC_NOT_IMPLEMENTED) 
           {
              System.err.println("The Post postmethod is not implemented by this URI");
               postmethod.getResponseBodyAsString();
           } 
             else if(rCode == HttpStatus.SC_NOT_ACCEPTABLE) {
                System.out.println(postmethod.getResponseBodyAsString());
          }
           else {
                      bufferedreader = new BufferedReader(new InputStreamReader(postmethod.getResponseBodyAsStream()));
                       String readLine;
        while(((readLine = bufferedreader.readLine()) != null)) {
          System.out.println("return value " +readLine);
      }
      }
    } catch (Exception e) {
      System.err.println(e);
    } finally {
      postmethod.releaseConnection();
      if(bufferedreader != null) try { bufferedreader.close(); } catch (Exception fe)    fe.printStackTrace();  }     }   }
}

Using this I get the return value for rCode as "406". Why am I receiving a response which is "Not Acceptable" Anything which would help me debug better and fix this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼前雾蒙蒙 2024-10-26 18:02:07

考虑使用记录请求和响应的代理。像 VisualProxy 这样的东西就可以了。我没有使用它,因为当我需要它时我自己编写了它。我的只是将请求写为页面正文。

Consider using a proxy which logs the request and response. Something like VisualProxy would do. I haven't used it as I wrote my own when I needed one. Mine just wrote the request out as the body of the page.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文