I would like to send HTTP Request with GET method, but I can't set the GET method.
Here's my code:
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("p1", "123")
.appendQueryParameter("p2", "123");
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
Log.e("ERROR", conn.getResponseMessage());
Log.e("ERROR", conn.getRequestMethod());
Log.e("ERROR", String.valueOf(conn.getResponseCode()));
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
In the code, I set GET method, but on the log, request method is POST:
02-01 16:48:54.766 23799-23831/? E/ERROR﹕ Method Not Allowed
02-01 16:48:54.766 23799-23831/? E/ERROR﹕ POST
02-01 16:48:54.766 23799-23831/? E/ERROR﹕ 405
What is a problem?
the problem is
conn.setDoOutput(true);
when set to true the request method is changed to POST, since GET or DELETE can't have a request body
Related
http://192.168.0.14/something/storeAnswerGet?longitude=20.49158053365199&latitude=44.798944935485885&answers="[{\"id\":3,\"id_question\":7,\"user_id\":1,\"answer\":\"Beograd\"},{\"id\":3,\"id_question\":7,\"user_id\":1,\"answer\":\"Valjevo\"},{\"id\":3,\"id_question\":8,\"user_id\":1,\"answer\":\"Da\"}]"
Problem is after &answers= it is not recognized as part of url,
that is a formatted JsonObject in string.
Explained here:
https://stackoverflow.com/a/27578923/1088975
Basically you have 2 options
Send data with POST method
Encode text and send with GET
Basically storeAnswer shall be post request and payload to be added on the request body with json format.
public void sendAnswerRequest(){
try {
URL url = new URL("http://192.168.0.14/something/storeAnswerGet");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept","application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("latitude", 44.798944935485885);
jsonParam.put("longitude", 20.49158053365199);
JSONArray answers = new JSONArray();
JSONObject answer = new JSONObject();
answer.put("id",3);
answer.put("id_question",7);
answer.put("user_id",1);
answer.put("answer","Beograd");
answers.put(answer); // Add all answers to answer array..
jsonParam.put("answers",answers);
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG" , conn.getResponseMessage());
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
I woluld like to make a raw HTTP GET request in Android setting custom cookie, however the code below works only with android from version 23 and later. With devices and emulators with version below 23 the code does not raise any exception but any cookie is added in the HTTP request (checked server side).
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
CookieHandler test =CookieHandler.getDefault();
HttpCookie lsd=null;
mycoockie= new HttpCookie("myc", coockie);
mycoockie.setDomain(domain);
mycoockie.setPath(path);
mycoockie.setVersion(0);
mycoockie.setMaxAge(-1);
try {
cookieManager.getCookieStore().add(new URI(basicuri), mycoockie);
} catch (URISyntaxException e) {
e.printStackTrace();
}
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
[...]
Thanks for any advice.
I got IOException when i try call getCodeResponse(). When parameters are valid there is no exception and code response is 200. In case of wrong parameteres server should return 401 code. I've tested query on hurl.it and in case of wrong parameters i got 401 code. Maybe HttpURLConnection class throws exception when error code occurs.
URL url = new URL(sUrl);
String charset = "UTF-8";
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(DEFAULT_TIMEOUT /* milliseconds */);
conn.setConnectTimeout(DEFAULT_TIMEOUT /* milliseconds */);
conn.setRequestMethod(methodType);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.addRequestProperty("Accept-Charset", charset);
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.addRequestProperty(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os));
writer.write(query);
writer.flush();
writer.close();
//os.write(query.getBytes());
os.flush();
os.close();
conn.connect();
if(conn != null){
responseCode = conn.getResponseCode();
result = readResponse(conn);
}
The IOException means that there is a 401 response. Print the stacktrace and if everything else is correct, it'll give a 401 response. Something like : java.io.IOException: Server returned HTTP response code: 401 for URL:
I'm trying to use HttpURLClient to send some POST data to a server using the HttpRestClient class shown below. When executing
conn.setDoInput(true);
I get
java.lang.IllegalStateException: Already connected
I uninstalled the app, and still get the same error.
In all the example I've seen openConnection is called before setDoInput. If, as its name suggests, openConnection opens a connection, it should never be used before `setDoInput, right? What am I missing?
Maybe at some point it crashed before executing disconnect. Could that be the reason? If so, how can I disconnect the old connection?
public class HttpRestClient {
static public int post(String urlStr, List<NameValuePair> data){
HttpURLConnection conn = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(data));
writer.flush();
writer.close();
os.close();
InputStream is = conn.getInputStream();
String dude = readIt(is);
return 1;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 0;
}
finally {
if(conn!=null) conn.disconnect();
}
}
}
This might be due to watches while debugging in your IDE. See this answer.
It happened to me and was hard to discover.
You called both of conn.setDoInput(true); and conn.setDoOutput(true);. Use one of them:
setDoOutput(true) is used for POST and PUT requests.
setDoInput(true) is used for GET request.
The connection you made was confused, it can't decide which request should be used.
In your code:
static public int post(String urlStr, List<NameValuePair> data){
HttpURLConnection conn = null;
System.setProperty("http.keepAlive", "false"); // must be set
try {
...
conn.setDoOutput(true);
conn.setRequestMethod("POST");
// and connect to server, if needed
conn.connect();
...
}
....
It may be a misleading exception. See this defect for Jersey-2 https://java.net/jira/browse/JERSEY-2729
The link has been updated:
https://github.com/javaee/jersey/issues/3001
Basically the issue is jersey was throwing invalid exception. The real issue in my case was that the connection was refused from the server.
I am trying to post a JSON message to a site and to retrieve a JSON message back.
java.net.ProtocolException: method does not support a request body: POST
Does anyone know what is wrong? Thanks in advance
HttpURLConnection conn=null;
try{
URL url=new URL(urlString);
String userPassword = userName +":" + passWord;
byte[] bytes=Base64.encode(userPassword.getBytes(),Base64.DEFAULT);
String stringEncoding = new String(bytes, "UTF-8");
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty ("Authorization", "Basic " + stringEncoding);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
Log.i("Net", "length="+conn.getContentLength());
Log.i("Net", "contentType="+conn.getContentType());
Log.i("Net", "content="+conn.getContent());
conn.connect();
}catch(Exception e){
Log.d("Url Formation Connection", e.toString());
}
//output{
try{
String requestString="{“ ";
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(requestString.toString());
wr.flush();
//input{
BufferedReader rd = null;
String response=" ";
is = conn.getInputStream();
rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer responseBuff = new StringBuffer();
while ((line = rd.readLine()) != null) {
// Process line...
responseBuff.append(line);
}
response = responseBuff.toString();
Log.d("response", response);
}catch(Exception e){
Log.d("buffer error", e.toString());
}finally {
if (is != null) {
try {
wr.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It could be that the server you're connecting to doesn't allow POST operations. I would try a GET request first, to see if you have permissions for that web service method.
Also, you could try your luck with a simpler HttpClient, although I haven't tested this solution myself: http://www.geekmind.net/2009/11/android-simple-httpclient-to.html
Just a guess but can you try setting:
conn.setDoOutput(false);
The documentation says: "Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body." HttpURLConnection
Since you do not have anything in your body, might as well set it to false.
The documentation Android has for setRequestMethod is minimal, however your error states that POST is not a valid method. Try using PUT instead:
conn.setRequestMethod("PUT");
Also see this post for any tweaks you may need to make.