开发者

Why connection is not establishing on first time?

开发者 https://www.devze.com 2023-03-28 20:36 出处:网络
I want to send my id & password to server and get the response from server. Here is my code. It is not working for the first time. But iam getting the response from server if i execute my applicat

I want to send my id & password to server and get the response from server. Here is my code. It is not working for the first time. But iam getting the response from server if i execute my application on second time. It is throwing "Post method failed: -1 null" on first time. Where iam wrong?? Why if() block is executing on first time?? could you please tell me.

HttpsURLConnection con = null;
String httpsURL = "https://www.abc.com/login";
String query = "id=xyz&password=pqr";
URL url = new URL(httpsURL); 
con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", String.valueOf(query.length()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent","Mozilla/4.0(compatible; MSIE 5.0; Windows 98; DigExt)"); 
con.setDoInput(true);
con.setDoOutput(true);  
DataOutputStream output = new DataOutputStream(con.getOutputStream());开发者_开发问答
output.writeBytes(query);
output.close();  
int respCode = con.getResponseCode();

if (respCode != HttpsURLConnection.HTTP_OK) 
{
  throw new Exception("POST method failed: " + con.getResponseCode()+ "\t" + con.getResponseMessage()); }
 else {
//read the content from server
}


1/ It is recommanded to use apache HttpClient rather than URLConnection (see http://developer.android.com/reference/org/apache/http/impl/client/DefaultHttpClient.html)

2/ for login and password, why not use Http Authentication ? both basic and digest are supported by android.

3/ as for you problem, you don't close the underlying outputStream.

you should do:

OutputStream os = con.getOutputStream();
DataOutputStream output = new DataOutputStream(os);
output.writeBytes(query);
output.close();
os.close();


Check Server service validity with other technology and/or classic java. You didn say in your question if you succeed to discriminate the server from the issue.

from java doc ...getResponseCode returns -1 if no code can be discerned from the response (i.e., the response is not valid HTTP).

Java https post request example : http://www.java-samples.com/java/POST-toHTTPS-url-free-java-sample-program.htm

try to close your outputstream after querying the status and not before...that may help


Here is how you should send POST requests in Android

HttpPost httpGet = new HttpPost(server + "/login?email="+username+"&password="+password);
DefaultHttpClient httpClient = new DefaultHttpClient();         
HttpResponse response = httpClient.execute(httpGet);

You can read response using:

response.getEntity().getContent()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号