I'm pretty new to making HTTP connections and working with API's in Java, so I'm not sure where the problem lies. When I send out a POST connection request in order to send a JSON formatted String of text to the other side, I get an error back along with a 400 response code. When I look up that code, it seems my connection isn't properly formatted. Code is below, along with the error message. Please help! Thanks!
public void sendToAPI(String urlPass, String param) throws IOException {
URL url = new URL(urlPass);
HttpURLConnection connectionOut = (HttpURLConnection) url.openConnection();
connectionOut.setRequestMethod("POST");
connectionOut.setConnectTimeout(5000);
connectionOut.setReadTimeout(5000);
connectionOut.setRequestProperty("Content-Type", "application/json");
connectionOut.setRequestProperty("Content-Length", Integer.toString(param.length()));
connectionOut.setDoOutput(true);
connectionOut.setDoInput(true);
connectionOut.connect();
DataOutputStream stream = new DataOutputStream(connectionOut.getOutputStream());
stream.writeUTF(param);
stream.flush();
stream.close();
int responsecode = connectionOut.getResponseCode();
if(responsecode != 200) {
System.out.println("Response Code is " + responsecode);
}
BufferedReader in = new BufferedReader(
new InputStreamReader(connectionOut.getInputStream()));
String output;
StringBuffer response = new StringBuffer();
while ((output = in.readLine()) != null) {
response.append(output);
}
in.close();
//printing result from response
System.out.println(response.toString());
}
Response Code is 400
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL:XXX
u can try this code:
InputStream inputStream;
if (responseCode == 200) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String lines;
while ((lines = reader.readLine()) != null) {
builder.append(lines);
builder.append(System.getProperty("line.separator"));
}
String retStr = builder.toString().trim();
reader.close();
System.out.println("retStr: " + retStr);
So after playing around with the DataOutputStream, I replaced the below code:
DataOutputStream stream = new DataOutputStream(connectionOut.getOutputStream());
stream.writeUTF(param);
With another example I found online:
OutputStream os = connectionOut.getOutputStream();
os.write(param.getBytes());
os.flush();
os.close();
I'm not sure yet why, but this suddenly got the proper response code I was looking for, so the format it was sent in matched what they requested. Thanks for all responses.
Related
Please check the code below. What the code does is use firstHttpConn to check the response code and open secondHttpConn. If the response code is 401, add a basic auth header to secondHttpConn. Then post the data and read the response.
However, the code throws Cannot write output after reading input error. I checked other questions on Stack Overflow like this one and I am sure I did not make the same mistakes.
//I hate using Java 6 and HttpURLConnection, but the code is for a very old system.
private static XmlObject callWebService(String soapMessage, String webServiceEndpoint, String soapAction) throws Exception {
XmlObject resultXMLObject;
HttpURLConnection firstHttpConn = null;
HttpURLConnection secondHttpConn = null;
try {
byte[] streamoutByteArray = soapMessage.getBytes("UTF-8");
URL url = new URL(webServiceEndpoint);
firstHttpConn = (HttpURLConnection) url.openConnection();
firstHttpConn.connect();
if (firstHttpConn.getResponseCode() == 401) {
firstHttpConn.disconnect();
secondHttpConn = (HttpURLConnection) url.openConnection();
secondHttpConn.setRequestProperty("Authorization", "Basic " + getBasicAuth());
} else {
firstHttpConn.disconnect();
secondHttpConn = (HttpURLConnection) url.openConnection();
}
secondHttpConn.setConnectTimeout(30000);
secondHttpConn.setReadTimeout(300000);
secondHttpConn.setRequestProperty("Content-Length", String.valueOf(streamoutByteArray.length));
secondHttpConn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8);
secondHttpConn.setRequestProperty("SOAPAction", soapAction);
secondHttpConn.setRequestMethod("POST");
secondHttpConn.setDoOutput(true);
secondHttpConn.setDoInput(true);
OutputStream out = secondHttpConn.getOutputStream();
out.write(streamoutByteArray);
out.close();
//Line 238 below.
InputStreamReader isr = new InputStreamReader(secondHttpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine;
StringBuffer sb = new StringBuffer();
while ((inputLine = in.readLine()) != null)
sb.append(inputLine).append("\n");
in.close();
resultXMLObject = XmlObject.Factory.parse(sb.toString());
} finally {
if (firstHttpConn != null)
firstHttpConn.disconnect();
if (secondHttpConn != null)
secondHttpConn.disconnect();
}
return resultXMLObject;
}
The log:
Caused By: java.net.ProtocolException: Cannot write output after reading input.
at weblogic.net.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:271)
at org.company.member.esb.webservice.WebServiceClient.callWebService(WebServiceClient.java:238)
at org.company.member.esb.webservice.WebServiceClient.invokeWebserviceV01(WebServiceClient.java:132)
at sun.reflect.GeneratedMethodAccessor711.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
Truncated. see log file for complete stacktrace
Anyone knows why? Thanks.
You're not running the code you pasted here. You can see the lines do not match, as there is HttpURLConnection.getOutputStream in the stack trace, but you claim
//Line 238 below.
InputStreamReader isr = new InputStreamReader(secondHttpConn.getInputStream());
so code is different for stack trace and your paste.
I don't see a problem with the code you've pasted here.
In my android application am reading text file which is in server.
Am using below method.
private String getUrlContents(String UrlOfFile)
{
StringBuilder content = new StringBuilder();
try
{
URL url = new URL(UrlOfFile);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
Log.d(TAG,"Exception >>>"+Log.getStackTraceString(e));
}
return content.toString();
}
But I am getting previous value of text file. When I once do clear data of app its able to get actual value.
Please help me to solve this issue.
My problem was due to returning of cached response.
Issue solved by urlConnection.setUseCaches(false);
Thanks to all responds,
How to prevent Android from returning a cached response to my HTTP Request?
Adding header for HttpURLConnection
I have created a code that checks if user is logged into Facebook. This is how it looks like:
URL url = new URL("https://graph.facebook.com/me?access_token=" + this.fb_token);
System.out.println("Attempting to open connection");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
int responseCode = conn.getResponseCode();
System.out.println(responseCode);
BufferedReader reader;
if(responseCode != 200) {
reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
}
else{
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
}
String json = reader.readLine();
reader.close();
conn.disconnect();
return json;
Next, I parse the Json, check if it's en error or data code and log the user.
My question is: Is if(responseCode != 200) check enough? Can Facebook return a different status code in case of successful authentication?
Hello I was wondering if somebody could help me with the following, I have a database that is currently populated. I used to call it using the http client and it worked fine but now I'm trying to update the code since its been deprecated to use the httpurlconnection but i have no success. I ve looked up some tutorials and tried a few thing but it doesn't seem to be working. the database is called through a php file and returns it in a json format.If i were to call the php file from my browser the response is the following: [{"id":"15","logo":"logo url","title":"title"}]
The error that I get on the console is the following:java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.InputStream.close()' on a null object reference
Which its not making much sense to me since the script pulls information
I have the following code, i left the commented section just in case i need any of it, It also includes the old way i used to call the DB Thank you!:
public void loadNews(){
InputStream is = null;
String result = "";
ArrayList<NameValuePair>();
try {
URL url = new URL("http://databasecall.php");
//HttpClient httpclient = new DefaultHttpClient();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("Content-length", "0");
//urlConnection.setUseCaches(false);
//urlConnection.setAllowUserInteraction(false);
//urlConnection.setConnectTimeout(15000);
//urlConnection.setReadTimeout(15000);
//urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
Log.i("Tag:", Integer.toString(responseCode)); //tag 200
//HttpPost httppost = new HttpPost("http://databasecall.php");
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//HttpResponse response = httpclient.execute(httppost);
//HttpEntity entity = response.getEntity();
//is = entity.getContent();
/*}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}*/
//convert response to string
//try{
//BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.i("Tag:", result);
}
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
Updated API
try {
String urlParameters = "name=toni&class=one¶m3=ok";
byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8"));
int postDataLength = postData.length;
String request = "http://rocks.php";
URL url = new URL(request);
HttpURLConnection cox = (HttpURLConnection) url.openConnection();
cox.setDoOutput(true);
cox.setDoInput(true);
cox.setInstanceFollowRedirects(false);
cox.setRequestMethod("POST");
cox.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
cox.setRequestProperty("charset", "utf-8");
cox.setRequestProperty("Content-Length",
Integer.toString(postDataLength));
cox.setUseCaches(false);
OutputStreamWriter writer = new OutputStreamWriter(
cox.getOutputStream());
writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(
cox.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
writer.close();
reader.close();
} catch (Exception e) {
result = e.toString();
Sucess = false;
e.printStackTrace();
}
I am new to android.So i can any one sho me how to make a http get request such as
GET /photos?size=original&file=vacation.jpg HTTP/1.1
Host: photos.example.net:80
Authorization: OAuth realm="http://photos.example.net/photos",
oauth_consumer_key="dpf43f3p2l4k3l03",
oauth_token="nnch734d00sl2jdk",
oauth_nonce="kllo9940pd9333jh",
oauth_timestamp="1191242096",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0",
oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D"
in android(java)?
You're gonna want to get familiar with InputStreams and OutputStreams in Android, if you've done this in regular java before then its essentially the same thing. You need to open a connection with the request property as "GET", you then write your parameters to the output stream and read the response through an input stream. You can see this in my code below:
try {
URL url = null;
String response = null;
String parameters = "param1=value1¶m2=value2";
url = new URL("http://www.somedomain.com/sendGetData.php");
//create the connection
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
//set the request method to GET
connection.setRequestMethod("GET");
//get the output stream from the connection you created
request = new OutputStreamWriter(connection.getOutputStream());
//write your data to the ouputstream
request.write(parameters);
request.flush();
request.close();
String line = "";
//create your inputsream
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
//read in the data from input stream, this can be done a variety of ways
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//get the string version of the response data
response = sb.toString();
//do what you want with the data now
//always remember to close your input and output streams
isr.close();
reader.close();
} catch (IOException e) {
Log.e("HTTP GET:", e.toString());
}