2012-10-11 183 views
6

我必須向web服務發送請求以使用用戶名和密碼對用戶進行身份驗證。JAVA:http發佈請求

我有以下POST請求的一個問題:

public String postTest(String action, ConnectionParametrData [] parameters) { 
     Uri.Builder builder = new Uri.Builder().scheme(scheme).authority(authority).path(action); 
     uri = builder.build(); 
     BufferedReader in = null; 
     String ans = null; 
     HttpPost request = new HttpPost(uri.toString()); 
     HttpClient defaultClient = new DefaultHttpClient(); 
     try { 
      request.setHeader("Content-Type", "application/x-www-form-urlencoded"); 
      request.setEntity(new UrlEncodedFormEntity(getValuePairs(parameters))); 
      HttpResponse response = defaultClient.execute(request); 
      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 8192); 
      StringBuffer sb = new StringBuffer(""); 
      String line = ""; 
      String newLine = System.getProperty("line.separator"); 
      while((line = in.readLine()) != null) { 
       sb.append(line + newLine); 
      } 
      ans = sb.toString(); 
     } catch (UnsupportedEncodingException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return ans; 
    } 

當我執行該方法服務器拋出錯誤告訴請求不是POST請求。

但這種方法的工作完美:

private String makePost(String action, ConnectionParametrData [] parameters) throws IOException { 
     StringBuilder urlBuild = new StringBuilder(); 
     urlBuild.append(scheme).append("://www.").append(authority).append(action); 
     URL url = new URL(urlBuild.toString()); 
     URLConnection urlConnection = url.openConnection(); 
     urlConnection.setDoInput(true); 
     urlConnection.setDoOutput(true); 
     urlConnection.setUseCaches(false); 
     urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

     DataOutputStream printout = new DataOutputStream(urlConnection.getOutputStream()); 

     String content = getParameters(parameters); 
     printout.writeBytes(content); 
     printout.flush(); 
     printout.close(); 

     BufferedReader in = null; 
     in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8192); 
     StringBuffer sb = new StringBuffer(""); 
     String line = ""; 
     String newLine = System.getProperty("line.separator"); 
     while((line = in.readLine()) != null) { 
      sb.append(line + newLine); 
     } 
     in.close(); 
     return sb.toString(); 
    } 

我更喜歡使用的HttpClient比URLConecction, 沒有任何人知道爲什麼第一個方法沒有被批准爲POST?

+1

「拋出錯誤」 - 以異常的形式?你有沒有檢查過線上的實際情況(WireShark)? – Fildor

+0

@wilek 你可以打印URI.toString()併發布它嗎? –

回答

0

在你的第一個代碼片段中,我沒有看到你在哪裏設置登錄和密碼的任何後期參數。

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair> { 
     new BasicNameValuePair("login", "myusername"), 
     new BasicNameValuePair("password", "somepassword")}; 
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

你可能想看看這個:http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient

0

@詹姆斯黑色

設置參數我有一個方法:

private List<NameValuePair> getValuePairs(ConnectionParametrData [] parameters) { 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
     if(parameters != null) { 
      for (ConnectionParametrData parameter : parameters) { 
       nameValuePairs.add(new BasicNameValuePair(parameter.getKey(), parameter.getValues())); 
      } 
     } 
     return nameValuePairs; 
    } 

@Fildor 異常是從服務器中拋出。

0
public String getPostPage(String postUrl, NameValuePair[] data, 
     String cookie) 
{ 
    String html = ""; 
    PostMethod method = null; 
    String contentStr = null; 
    try 
    { 
     method = new PostMethod(postUrl); 
     method.addRequestHeader("User-Agent", USER_AGENT); 
     method.addRequestHeader("Host", "asqx.moni.gucheng.com"); 
     method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); 
     method.addRequestHeader("Referer", "..."); 
     method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); 
     method.addRequestHeader("Cookie", cookie); 
     method.addRequestHeader("X-MicrosoftAjax", "Delta=true"); 
     method.addRequestHeader("Pragma", "no-cache"); 
//   method.addRequestHeader("Accept-Encoding", "gzip, deflate"); 
     method.addRequestHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7"); 
     method.addRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
     method.addRequestHeader("Accept-Language", "zh-cn,zh;q=0.5"); 
     method.setRequestBody(data); 
     int statusCode = client.executeMethod(method); 

     if(statusCode == HttpStatus.SC_OK) 
     { 
      InputStream in = method.getResponseBodyAsStream(); 
      if (in != null) { 
       byte[] tmp = new byte[4096]; 
       int bytesRead = 0; 
       ByteArrayOutputStream buffer = new ByteArrayOutputStream(1024); 
       while ((bytesRead = in.read(tmp)) != -1) { 
        buffer.write(tmp, 0, bytesRead); 
       } 
       byte[] bt = buffer.toByteArray(); 
       String gbk = new String(bt, "GBK"); 
       String utf8 = new String(bt, "UTF-8"); 
       if (gbk.length() < utf8.length()) { 
        bt = null; 
        bt = gbk.getBytes("UTF-8"); 
        html = new String(bt, "UTF-8"); 
        html = html.replaceFirst(
            "[cC][hH][aA][rR][sS][eE][tT]\\s*?=\\s*?([gG][bB]2312|[gG][bB][kK]|[gG][bB]18030)", 
            "charset=utf-8"); 
       } else if (gbk.length() > utf8.length()) { 
        html = buffer.toString(); 
       } else { 
        html = buffer.toString(); 
       } 
       buffer.close(); 
       contentStr = new String("abc".getBytes(), "UTF-8"); 
       contentStr = html; 

       in.close(); 
       in = null; 
      } 
     } 
     else 
     { 
      contentStr = null; 
     } 
    } catch (Exception e) 
    { 
     log.error(e); 
    } finally 
    { 
     if (method != null) 
      method.releaseConnection(); 
    } 
    return contentStr; 
} 

我用的評判來發布和獲取回報的內容。希望可以幫助你。