Please give very simple basic POST command code for android studio - android

I want to send a simple POST command to upload files. How can I write the code in android developer? Code should give the following POST request
POST /macros/s/AqtUErjtk/postform?no&func=uploadFiles HTTP/1.1
Host: xyz.website.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: multipart/form-data; boundary=---------------------------236532717524914
Content-Length: 337
Cookie:
NID=106=gWQeUVIa2phdDJeXYdRFSPTnsklPrFVRwphw3G685QYZlDiZz7NK5PoJVEd1FYL6IqYoJ9fEtVHf0sKBIHq1wD1xr
Connection: close
Upgrade-Insecure-Requests: 1
-----------------------------236532717524914
Content-Disposition: form-data; name="_1_myFile"; filename="textfile.txt"
Content-Type: text/plain
Here is the text file content yoyoyoyoyoy
-----------------------------236532717524914--

In the following link you will see an example in which a POST is made:
https://community.particle.io/t/example-android-application-post-get/9355
This is the exact code extracted from the link above:
class PostClient extends AsyncTask<String, Void, String> {
public String doInBackground(String... IO) {
// Predefine variables
String io = new String(IO[0]);
URL url;
try {
// Stuff variables
url = new URL("https://api.spark.io/v1/devices/YOURCOREID/SCL/");
String param = "access_token=YOURACCESSTOKEN&params=d7,"+io;
Log.d(TAG, "param:" + param);
// Open a connection using HttpURLConnection
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setReadTimeout(7000);
con.setConnectTimeout(7000);
con.setDoOutput(true);
con.setDoInput(true);
con.setInstanceFollowRedirects(false);
con.setRequestMethod("POST");
con.setFixedLengthStreamingMode(param.getBytes().length);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Send
PrintWriter out = new PrintWriter(con.getOutputStream());
out.print(param);
out.close();
con.connect();
BufferedReader in = null;
if (con.getResponseCode() != 200) {
in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
Log.d(TAG, "!=200: " + in);
} else {
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
Log.d(TAG, "POST request send successful: " + in);
};
} catch (Exception e) {
Log.d(TAG, "Exception");
e.printStackTrace();
return null;
}
// Set null and we´e good to go
return null;
}
}
}
I hope it helps.

Related

Android could not receive form submit response

I have a python webserver, which is listening for connections, and responds to them based on the request. The portion of code on python server of interest is POST request (http://192.168.0.1/conf_wifi_app.html). It takes 4 arguments
username (admin)
password (admin)
essid (Home wifi network SSID)
passphrase (Home wifi network password)
On python server, after the post body parameters are validated, a response is to be sent like so (notice I've put logs for debugging):
json_response = '{"error":false,' + '"code":"' + str(activation_code) + '","mac":"' + str(macaddress) + '","message":"Device configured successfully"}'
bytes_sent = client_s.send(json_response)
client_s.close()
print("Bytes sent " + str(bytes_sent))
print("json_response : " + json_response)
where client_s is the client socket. "send" function on socket should send the response (json_response), and then we close the socket. Logs print the number of bytes which is actually sent.
The client responds perfectly well when POST request is done from the web browser or from postman plugin. Just for some reference, I've put the raw request when invoked from postman plugin on chrome browser:
POST /conf_wifi_app.html HTTP/1.1
Host: 192.168.0.1
Connection: keep-alive
Content-Length: 67
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/68.0.3440.75 Chrome/68.0.3440.75 Safari/537.36
Cache-Control: no-cache
Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
Postman-Token: 4f4a14a7-857d-666f-a2db-279731c83b4a
Content-Type: application/x-www-form-urlencoded
Accept: /
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
essid=NETGEAR-XXXX&passphrase=XXXXXXXX&username=admin&password=admin&submit=submit
The response is received when the POST request is made from web browser (or postman). Now I was trying to create an android app which does the same POST request as follows:
HttpURLConnection urlConnection = null;
try {
Map<String,Object> params = new LinkedHashMap<>();
params.put("user", Constants.DEVICE_DEFAULT_USER);
params.put("username", Constants.DEVICE_DEFAULT_USER);
params.put("password", Constants.DEVICE_DEFAULT_PASSWORD);
params.put("essid", homeWifiSSID.replaceAll("^\"|\"$", ""));
params.put("passphrase", homeWifiPassword);
StringBuilder urlParameters = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (urlParameters.length() != 0) urlParameters.append('&');
urlParameters.append(URLEncoder.encode(param.getKey(), "UTF-8"));
urlParameters.append('=');
urlParameters.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postData = urlParameters.toString().getBytes("UTF-8");
int postDataLength = postData.length;
URL url = new URL(Constants.DEVICE_CONFIG_URL);
urlConnection = (HttpURLConnection) network.openConnection(url);
urlConnection.setDoInput( true );
urlConnection.setDoOutput( true );
urlConnection.setInstanceFollowRedirects( false );
urlConnection.setRequestMethod( "POST" );
urlConnection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty( "charset", "utf-8");
urlConnection.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
urlConnection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8");
urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
urlConnection.setUseCaches( false );
urlConnection.setConnectTimeout(OuroborosAPI.CONNECTION_TIMEOUT);
urlConnection.setReadTimeout(OuroborosAPI.CONNECTION_TIMEOUT);
try( DataOutputStream wr = new DataOutputStream( urlConnection.getOutputStream())) {
wr.write( postData );
wr.flush();
wr.close();
}
Reader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
for (int c; (c = in.read()) >= 0;) {
System.out.print((char) c);
}
}
catch (Exception e) {
}
From android app, the post raw data received is as follows:
POST /conf_wifi.html HTTP/1.1
Content-Type: application/x-www-form-urlencoded
charset: utf-8
Content-Length: 85
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8
User-Agent: Dalvik/2.1.0 (Linux; U; Android 7.1.1; Moto G (5S) Plus Build/NPSS26.116-61-11)
Host: 192.168.0.1
Connection: Keep-Alive
Accept-Encoding: gzip
essid=NETGEAR-XXXX&passphrase=XXXXXXXX&username=admin&password=admin&submit=submit
The python socket in this case does send data (as confirmed from the logs), but the android errors out saying unexpected end of string.
I've literally tried every thing (like adding extra headers, etc) but to no avail. Please help or suggest where I may be going wrong.
The problem was not that I was not sending \n ended lines, or not using readline()
I was not sending the HTML raw headers like so
HTTP/1.1 200 OK
Content-Length: 9328
Content-Type: text/html
... Actual content/payload....
Once I sent the headers also, the code worked without any problems.

Receiving "501 Not Implemented" when using HttpURLConnection

My project is targeted to SDK 23, and from now on, as far as I know, I have to use HttpURLConnection instead of HttpClient to make post requests, but I keep getting 501 response code from my webservice (I'm pretty sure it's fully functional, I have no doubt) when making post requests to store users in a remote mysql database. Here follows the main connection code:
class DatabaseConnector extends AsyncTask<String, Void, String> {
private final String CONNECTION_URL = "webservice_address";
#Override
protected String doInBackground(String... params) {
String response = "initial value";
try {
URL url = new URL(CONNECTION_URL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("POST");
JSONObject json = new JSONObject();
json.put("query", params[0]);
JSONObject conn = new JSONObject();
conn.put("database", "database");
conn.put("hostname", "hostname");
conn.put("password", "password");
conn.put("username", "username");
conn.put("port", "port");
json.put("conn", conn.toString());
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(json.toString());
wr.flush();
wr.close();
con.connect();
//display what returns the POST request
StringBuilder sb = new StringBuilder();
int HttpResult = con.getResponseCode();
System.out.println("Response CODE: "+ con.getResponseCode());
if (HttpResult == HttpURLConnection.HTTP_OK) {
System.out.println("Passed1");
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
while ((response = br.readLine()) != null) {
sb.append(response + "\n");
}
br.close();
System.out.println("E: " + sb.toString());
response = sb.toString();
} else {
System.out.println("E2: "+con.getResponseMessage());
response = "Error1: "+con.getResponseMessage();
}
} catch (Exception e) {
response = "Error2: "+e.toString();
}
return response;
}
}
And in my fragment I make the network calls:
try {
String result = new DatabaseConnector().execute("SELECssT 1").get();
Toast.makeText(ContentActivity.this, "Result: "+result, Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(ContentActivity.this, "Error3: "+ex.toString(), Toast.LENGTH_LONG).show();
}
Nevermind that wrong sql statement, it's meant to be like that, I want the webservice to echo back that syntax error. I have tried many stuff, codes, examples, but it doesn't seem to work.
The point is: I keep getting error code 501 Not Implemented. Why? And how can I fix that?
EDIT:
Any tips or comments on how to improve the way I make network calls on android is welcome, I'm pretty new to that. I'm using a Async call but somehow it's still executing in the main thread, cause the debugger complains:
09-25 19:17:32.714 28853-28853/br.com.developer.package I/Choreographer﹕ Skipped 80 frames! The application may be doing too much work on its main thread.
Thank you all.

How to send HTTP request using JWT token for authentication from cookie storage in android

What I did so far:
I am trying to communicate with Java web application which has custom authentication. In that, I need to first hit a link with request body parameters JSON type to get JWT auth-token in my cookies.
I have tested connection in Postman, I am receiving proper JSON response. But when I try same in my android application it return Bad Request error.
For Postman testing:
For login and getting auth-token in cookie storage:
Post, URL: http://iitjeeacademy.com/iitjeeacademy/api/v1/login
Headers: Content-Type:application/json
Request body (raw): {"password":"123","type":"student","email":"shobhit#gmail.com"}
After login getting response using:
Get, URL: http://iitjeeacademy.com/iitjeeacademy/api/v1/student/me
Screenshot of cookie stored in Postman:
Screenshot of cookie stored in Chrome
Following are my HttpURLConnection request codes in android:
"Post" method, this connection is used to get auth-token. This method returns 200 Response.
HttpURLConnection connection = null;
try {
// Created URL for connection.
URL url = new URL(link);
// Input data setup
byte[] postData = request.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
// Created connection
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
connection.setUseCaches(false);
// loaded inputs
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.write(postData);
wr.flush();
wr.close();
// getting a response
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
// Read response
response = convertToString(connection.getInputStream());
return response;
}else{
// Read Error
String response = connection.getResponseMessage();
return response;
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.v("MalformedURL ---> ", e.getMessage());
} catch (ProtocolException p) {
p.printStackTrace();
Log.v("Connection ---> ", p.getMessage());
} catch (IOException i) {
i.printStackTrace();
Log.v("IO Exception ---> ", i.getMessage());
} finally {
connection.disconnect();
}
"Get" method, must have auth-token in session cookies to get response. This method gives an 401 Unauthorized Error.
HttpURLConnection connection = null;
try{
// Created URL for connection
URL url = new URL(link);
// Created connection
connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
// getting a response
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
response = convertToString(connection.getInputStream());
return response;
}else{
// Read Error
String response = connection.getResponseMessage();
return response;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException p) {
p.printStackTrace();
} catch (IOException i) {
i.printStackTrace();
} finally {
connection.disconnect();
}
Question:
How to use stored JWT Token from cookies in HttpURLConnection android to get response from web service.
I'm sure you've moved on, but...
For JWT auth, I'd send an HTTP Request header formatted as:
Authorization: Bearer jwtHeader.jwtPayload.jwtSignature
EXAMPLE:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
The specification and details are available at: https://jwt.io/introduction/
Building on jaygeek's answer (set the Authorization header and 'Bearer ' prefix) with an overly simplified JavaScript-client example:
localStorage.jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ';
fetch('/api/example', {method: 'POST',
headers: {
'Authorization':`Bearer ${localStorage.jwt}`,
'Content-type':'application/json'
}, body: JSON.stringify({stuff:'things'})
})
.then(console.log).catch(console.error);
function jwtRequest(url, token){
var req = new XMLHttpRequest();
req.open('get', url, true);
req.setRequestHeader('Authorization','Bearer '+token);
req.send();
}
jwtRequest('/api/example', localStorage.jwt);

Android HttpUrlConnection Cannot Post - Error 403

I'm trying to issue a HttpPost against my webservice with spring security csrf.
first, I'm trying to recover the XSRF TOKEN through a GET request, like this
public static CookieManager xcsrfToken() throws IOException{
String token;
URL url = new URL(urlBase);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
CookieManager cookieManager = new CookieManager();
con.connect();
List<String> cookieHeader = con.getHeaderFields().get("Set-Cookie");
if (cookieHeader != null) {
for (String cookie : cookieHeader) {
cookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
}
}
System.out.println(con.getHeaderFields());
con.disconnect();
return cookieManager;
}
This is what i get from the con.getHeaderFields()
{null=[HTTP/1.1 200 OK], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Content-Language=[pt-BR], Content-Length=[973], Content-Type=[text/html;charset=ISO-8859-1], Date=[Wed, 19 Aug 2015 10:40:18 GMT], Expires=[0], Pragma=[no-cache], Server=[Apache-Coyote/1.1], Set-Cookie=[JSESSIONID=6C9326FBEEA14752068720006F2B5EAA; Path=/webapi/; HttpOnly, XSRF-TOKEN=07cbed7f-834e-4146-8537-0a6b5669f223; Path=/], X-Android-Received-Millis=[1439980819720], X-Android-Response-Source=[NETWORK 200], X-Android-Sent-Millis=[1439980819693], X-Content-Type-Options=[nosniff], X-Frame-Options=[DENY], X-XSS-Protection=[1; mode=block]}
The XSRF-TOKEN is in my cookie, ok!
If I print then with
System.out.println(cookieManager.getCookieStore().getCookies());
I got this
[JSESSIONID=5B1D3E2D3E7B3E1E6572A3839BFF3741, XSRF-TOKEN=4d4048bd-f21c-48c6-895e-5f67523ad963]
Now, I'm trying to issue a POST against the server, like this
public static HttpURLConnection makeRequest(String metodo, String uri, String requestBody) throws IOException{
URL url = new URL(urlBase + uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(!metodo.equals("GET"));
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Cookie", TextUtils.join("," , xcsrfToken().getCookieStore().getCookies()));
con.connect();
InputStream is = con.getErrorStream();
System.out.println(IOUtils.toString(is, "UTF-8"));
System.out.println(con.getHeaderFields());
return con;
}
But the header is comming back without the cookies
{null=[HTTP/1.1 403 Forbidden], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Content-Language=[en], Content-Length=[1149], Content-Type=[text/html;charset=utf-8], Date=[Wed, 19 Aug 2015 10:42:18 GMT], Expires=[0], Pragma=[no-cache], Server=[Apache-Coyote/1.1], X-Android-Received-Millis=[1439980939827], X-Android-Response-Source=[NETWORK 403], X-Android-Sent-Millis=[1439980939811], X-Content-Type-Options=[nosniff], X-Frame-Options=[DENY], X-XSS-Protection=[1; mode=block]}
And it says that don't have a CSRF valid token
Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-XSRF-TOKEN'.
In my webservice, the tokens is configured to rename to XSRF-TOKEN because of angularJs.
SOLUTION
public static void getTokens() throws IOException{
URL url = new URL(urlBase);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.connect();
cookieManager = new CookieManager();
List<String> cookieHeader = con.getHeaderFields().get("Set-Cookie");
if (cookieHeader != null) {
for (String cookie : cookieHeader) {
String[] tokens = TextUtils.split(cookie, "=");
if (tokens[0].equals("JSESSIONID"))
cookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
if (tokens[0].equals("XSRF-TOKEN")) {
String[] tokenValue = TextUtils.split(tokens[1],";");
xsrfTOKEN = tokenValue[0];
}
}
}
con.disconnect();
}
Then, attach it to HttpUrlConnection
con.setRequestProperty("X-XSRF-TOKEN", xsrfTOKEN);
As I have experienced, we would need to submit the token as a request header. Spring expects its name to be X-CSRF-TOKEN by default. But people using AngularJS normally alter it to X-XSRF-TOKEN in Spring Security configuration.
But looking at your code, I couldn't figure out if you are sending that header.
If it would help, here is a snippet from my one project (using RestAssured):
if (xsrfToken != null && !ctx.getRequestMethod().equals(Method.GET))
requestSpec.header("X-XSRF-TOKEN", xsrfToken);

HTTPURLConnection - 400 Bad Request

I check this Post. But I don't still understand what the logical error could be. I am still getting this error. I tried to dump the emulator traffic. But I still don't get my head around what the problem could be.
From the traffic dump, this is what Android is sending as request to the server. You can see the response too:
GET /Authenticate/ HTTP/1.1
Authorization: Basic asdfasdfasdfas
Accept-Charset: UTF-8
Host: www.domain.com
User-Agent: Dalvik/1.4.0 (Linux; U; Android 2.3.3; sdk Build/GRI34)
Connection: Keep-Alive
Accept-Encoding: gzip
neQPˆ? 6 6 RT 4VRT 5 E (
» #ÍCl¦'
PÙ[ ˜ároP"8" neQPI " " RT 4VRT 5 E
¼ #ËVl¦'
PÙ[ ˜ároP"8«‹ HTTP/1.1 400 Bad Request
Date: Thu, 13 Sep 2012 04:47:42 GMT
Server: Apache/2.2.15 (CentOS)
Content-Length: 310
Connection: close
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.2.15 (CentOS) Server at www.domain.com Port 80</address>
</body></html>
neQPé¬ 6 6 RT 4VRT 5 E (
½ #ÍAl¦'
PÙ[ ™îároP"8 , neQPéË # # RT 5RT 4V E (çØ# #³-
l¦'Ù[ Páro ™îP )E neQPéË # # RT 5RT 4V E (çÙ# #³,
l¦'Ù[ Páro ™ïP )D neQPö“
© © RT 5RT 4V E ›k‹# #¶Á
³ër,9Jr ‘Pÿÿ6B WRTE w [ * ¨­«º[ 09-13 04:47:41.822 446:0x1c7 D/400 ]
text/html; charset=iso-8859-1Bad Request
I don't know what those extra characters mean. But I was trying to identify the problem from it.
This is the basic code:
String credentials = username + ":" + password;
byte[] toencode = null;
try {
toencode = credentials.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
HttpURLConnection conn = null;
try {
//Utilities.isNetworkAvailable(context);
URL url = new URL(params[0]);
Log.d(params[0],"UR");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(toencode, Base64.DEFAULT));
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Host", "www.domain.com");
conn.setRequestMethod("GET");
conn.setDoOutput(true);
String data = conn.getInputStream().toString();
return data;
}
Any ideas?
Update
I checked Webserver Logs to see if the requests are hitting the server and if there was any problem with the request. This is what I see from error logs:
[Thu Sep 13 10:05:24 2012] [error] [client 91.222.195.132] client sent HTTP/1.1 request without hostname (see RFC2616 section 14.23): /Authenticate/
[Thu Sep 13 23:11:57 2012] [error] [client 91.222.195.132] client sent HTTP/1.1 request without hostname (see RFC2616 section 14.23): /Authenticate/
[Thu Sep 13 23:12:03 2012] [error] [client 91.222.195.132] client sent HTTP/1.1 request without hostname (see RFC2616 section 14.23): /Authenticate/
However I am setting the header property for the request.
Any ideas?
I figured out this myself. Its an issue with the order of setting headers.
Edit: Order I used.
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Host", "myhost.com");
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(toencode, Base64.DEFAULT));
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:1.3.1)");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setConnectTimeout (5000) ;
conn.setDoOutput(true);
conn.setDoInput(true);
I was also facing this issue, but i fixed it by changing my codes, now i am using following lines of codes
BufferedReader reader;
StringBuffer buffer;
String res = null;
try {
URL url = new URL(request_url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(40000);
con.setConnectTimeout(40000);
con.setRequestMethod("GET");
con.setRequestProperty("Accept","application/json");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoInput(true);
con.setDoOutput(true);
int status = con.getResponseCode();
InputStream inputStream;
if (status == HttpURLConnection.HTTP_OK) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}
reader = new BufferedReader(new InputStreamReader(inputStream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
res = buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
Try this
static final String _url = "http://www.google.com";
static final String charset = "UTF-8";
// to build the query string that will send the message
private static String buildRequestString(String param1,
String param2, String param3, String param4, String param5)
throws UnsupportedEncodingException {
String[] params = new String[5]; //customize this as per your need
params[0] = param1;
params[1] = param2;
params[2] = param3;
params[3] = param4;
params[4] = param5;
String query = String.format(
"uid=%s&pwd=%s&msg=%s&phone=%s&provider=%s",
URLEncoder.encode(params[0], charset),
URLEncoder.encode(params[1], charset),
URLEncoder.encode(params[2], charset),
URLEncoder.encode(params[3], charset),
URLEncoder.encode(params[4], charset));
return query;
}
public static void doSomething(String param1, String param2,
String param3, String param4, String param5) throws Exception {
// To establish the connection and perform the post request
URLConnection connection = new URL(_url
+ "?"
+ buildRequestString(param1, param2, param3, param4,
param5)).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
// This automatically fires the request and we can use it to determine
// the response status
InputStream response = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(response));
// This stores the response code.
// Any call to br.readLine() after this is null.
responsecode = br.readLine();
// And this logs the already stored response code
Log.d("ServerResponse", responsecode);
responseInt = Integer.valueOf(responsecode).intValue();
}

Categories

Resources