我是android新手。我正在尝试http post请求但是连接失败了。以下是给定的代码
private void postRequest(String givenUsername, String givenPassword) {
String paramUsername = givenUsername;
String paramPassword = givenPassword;
System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword);
HttpClient httpClient = new DefaultHttpClient();
// In a POST request, we don't pass the values in the URL.
// Therefore we use only the web page URL as the parameter of the HttpPost argument
HttpPost httpPost = new HttpPost("url");
httpPost.addHeader("Content-Length", "40");
httpPost.addHeader("Accept", "application/json,text/javascript, */*");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
// httpPost.s
// Because we are not passing values over the URL, we should have a mechanism to pass the
// values that can be
// uniquely separate by the other end.
// To achieve that we use BasicNameValuePair
// Things we need to pass with the POST request
BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("username", paramUsername);
BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("password", paramPassword);
// We add the content that we want to pass with the POST request to as name-value pairs
// Now we put those sending details to an ArrayList with type safe of NameValuePair
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
nameValuePairList.add(passwordBasicNameValuePAir);
try {
// UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs.
// This is typically useful while sending an HTTP POST request.
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
// setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
httpPost.setEntity(urlEncodedFormEntity);
try {
// HttpResponse is an interface just like HttpPost.
// Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
Log.i("RESPONSE", EntityUtils.toString(resEntity));
}
// According to the JAVA API, InputStream constructor do nothing.
// So we can't initialize InputStream although it is not an interface
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
System.out.println("Initial set of cookies:");
List<Cookie> cookies = ((AbstractHttpClient) httpClient).getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
System.out.println("Post logon cookies:");
cookies = ((AbstractHttpClient) httpClient).getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
}
我正在为我的登录屏幕发送用户名和密码。它将返回给我一个cookie。 任何帮助将不胜感激。
答案 0 :(得分:0)
在以下一行
HttpPost httpPost = new HttpPost("url");
将url
替换为您的网址
编辑: 以下是我通过我的网址的方式:
String url_select = "http://www.yoururlgoeshere.com"
HttpPost httpPost = new HttpPost(url_select);
此外,由于我使用的是API Level 3.0+,我必须使用AsyncTask
来使用HTTP Post。这是tutorial link。
答案 1 :(得分:0)
此方法适用于每个请求。 “POST”以字符串形式给出。
* Sends generic HTTP calls: GET, POST, DELETE etc provided the parameters. Also includes the
* response body in the returned object.
*/
private WebCallResponse sendRequest(String url, WebCallHeader[] headers,
String method, byte[] postBytes) throws WebServiceException
{
HttpURLConnection conn = null;
URL serverUrl = null;
OutputStream os = null;
InputStream is = null;
try
{
serverUrl = new URL(url);
conn = (HttpURLConnection)serverUrl.openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("Accept-Encoding", "deflated");
conn.setRequestProperty("Accept-Ranges", "bytes");
if(headers != null && headers.length > 0)
{
for(int i = 0; i < headers.length; ++i)
{
conn.setRequestProperty(headers[i].getHeaderName(), headers[i].getHeaderValue());
}
}
//-- For POSTs and PUTs
if(postBytes != null && postBytes.length > 0)
{
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", String.valueOf(postBytes.length));
conn.connect();
os = conn.getOutputStream();
os.write(postBytes);
}
//-- Execute happens here.
final int rc = conn.getResponseCode();
//-- Build return object from the response.
final WebCallResponse wcr = new WebCallResponse();
wcr.setStatusCode(rc);
if (conn.getHeaderField("record-count") != null)
{
final Vector headerVector = new Vector();
headerVector.add(conn.getHeaderField("record-count"));
wcr.setHeaders(headerVector);
}
is = new BufferedInputStream(conn.getInputStream());
wcr.setResponseString(this.getResponseBody(is));
return wcr;
} catch(IOException ioe)
{
conn.getErrorStream();
throw new WebServiceException(ioe, "Failed to open connection to host.");
}finally
{
try{if(is != null)is.close();}catch(Exception squish){}
try{if(os != null)os.close();}catch(Exception squish){}
try{if(conn != null)conn.disconnect();}catch(Exception squish){}
}
}
public class WebCallResponse {
private int statusCode;
private String responseString;
private Vector headers;
public Vector getHeaders()
{
return headers;
}
public void setHeaders(Vector headers)
{
this.headers = headers;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public int getStatusCode() {
return statusCode;
}
public void setResponseString(String responseString) {
this.responseString = responseString;
}
public String getResponseString() {
return responseString;
}
public boolean isRequestSuccessful(){
return (statusCode >=200 && statusCode <300);
}
public String getHeaderValue(String key)
{
WebCallHeader currentHeader;
String result = null;
for (int i = 0; i < this.headers.size(); i++)
{
currentHeader = ((WebCallHeader) this.headers.elementAt(i));
if (currentHeader.getHeaderName().equalsIgnoreCase(key))
{
result = currentHeader.getHeaderValue();
}
}
return result;
}
public String toString()
{
return this.responseString;
}
}
public class WebCallHeader {
private String headerName;
private String headerValue;
public WebCallHeader(String name,String value)
{
this.headerName = name;
this.headerValue = value;
}
public void setHeaderName(String headerName) {
this.headerName = headerName;
}
public String getHeaderName() {
return headerName;
}
public void setHeaderValue(String headerValue) {
this.headerValue = headerValue;
}
public String getHeaderValue() {
return headerValue;
}
}