I am fairly confident this code works (I used it in another part of my project for a different API) as far as posting but I do not think the URL is being formatted correctly. I want to know if there is anyway to view the full URL after building all of the entities so I can see if the final URL is formatted correctly. Code:
My URL = http://pillbox.nlm.nih.gov/PHP/pillboxAPIService.php
Method = POST
API key = not going to post (works though)
drugName = just a string that has the name of a drug
I have logs in the code to try and view the url but they aren't returning anything close and the debugger isn't either.
I am trying to build the URL to look like this:
http://pillbox.nlm.nih.gov/PHP/pillboxAPIService.php?key=My_API_KEY&ingredient=diovan
public String makeServiceCallPillBox(String url, int method,
String api, String drugName)
{
String resultEnitity = null;
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpEntity entityResult = null;
// Checking http request method type
if (method == POST)
{
HttpPost httpPost = new HttpPost(url);
// Butild the parameters
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addTextBody("key", api);
builder.addTextBody("ingredient", drugName);;
final HttpEntity entity = builder.build();
httpPost.setEntity(entity);
Log.d("url", httpPost.toString());
httpResponse = httpClient.execute(httpPost);
Log.d("post", builder.toString());
Log.d("post2", entity.toString());
entityResult = httpResponse.getEntity();
resultEnitity = EntityUtils.toString(entityResult);
Log.d("result", resultEnitity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resultEnitity;
}
Any help is appreciated.
Related
I´m currently working on an app and having my problems with uploading a JSONObject to my Iris CouchDb. But I can´t get it to work.
This is the code I´m using right now:
private class MyHttpPost extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... arg0)
{
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost("https://dbname.iriscouch.com/dbname");
try {
// Add your data
JSONObject jsonDoc = new JSONObject();
try {
jsonDoc.put("name", "test");
jsonDoc.put("autor", "test author");
jsonDoc.put("rundgangnr", "1");
jsonDoc.put("latitude", 58.0);
jsonDoc.put("longitude", 7.88);
} catch (JSONException e) {
e.printStackTrace();
} // end try
String body = jsonDoc.toString();
StringEntity entity = new StringEntity(body, "utf-8");
httpPost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
InputStream result = httpEntity.getContent();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return true;
}
}
In onCreate I do this to execute the function:
new MyHttpPost().execute();
When I run the app, there are no errors but nothing gets uploaded. So there isn´t any change in the database.
Am I using the wrong URL to upload it on Iris or is there something wrong with the code? I´m new to Android development and really would appreciate your help as I have been struggling with this for days now.
Perhaps you need to use https://accountname.iriscouch.com/dbname rather than https://dbname.iriscouch.com/dbname.
Also, if the request throws an IOException, your app will be silently swallowing the error so you might not be seeing it.
I've been trying to get a simple android client server app working, and I've had nothing but trouble. I'm hoping someone can look at this code and see what I'm doing wrong, maybe I'm doing things in the wrong order, or forgetting something? Just adding the relevant parts
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.addRequestProperty("Content-Type", "application/json");
// set some made up parameters
String str = "{'login':'superman#super.com','password':'password'}";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
// connection.setDoOutput(true); //should trigger POST - move above -> crash
conn.setRequestMethod("POST"); // explicitly set POST -move above so we can set params -> crash
conn.setDoInput(true);
The error I get is
'exception: java.net.ProtocolException: method does not support a
request body: GET'
If I just do a POST request without parameters it's fine, so I guess I should move the connection.setDoOutput(true); or conn.setRequestMethod("POST"); higher up, that should work right? When I do that I get the error:
exception: java.net.ProtocolException: Connection already established.
So, if I try to set to POST before adding parameters it doesn't work, if I try to do it after it doesn't work... what am I missing? Is there another way I should be doing this? Am I adding parameters incorrectly? I've been searching for a simple android networking example, and I can't find any, is there any example the official Android site? All I want to do is a very basic network operation, this is so frustrating!
EDIT: I need to use HttpsURLConnection for reasons not included in the above code- I need to authenticate, trust hosts, etc- so I'm really looking for a potential fix for the above code if possible.
Here is an example of how to post with a JSON Object:
JSONObject payload=new JSONObject();
try {
payload.put("password", params[1]);
payload.put("userName", params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
String responseString="";
try
{
HttpPost httpPost = new HttpPost("www.theUrlYouQWant.com");
httpPost.setEntity(new StringEntity(payload.toString()));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse response = new DefaultHttpClient().execute(httpPost);
responseString = EntityUtils.toString(response.getEntity());
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
And example of how to get
String responseString = "";
//check if the username exists
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("www.theUrlYouQWant.com");
ArrayList<String> existingUserName = new ArrayList<String>();
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
else
{
Log.e(ParseException.class.toString(), "Failed to download file");
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
I followed this tutorial on making http calls:
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Works fine with no problems.
Below is a class that I have modified from the sample:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
String TAG = ((Object) this).getClass().getSimpleName();
public ServiceHandler() {
}
/**
* Making service call
*
* #url - url to make request
* #method - http request method
*/
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
*
* #url - url to make request
* #method - http request method
* #params - http request params
*/
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 2000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 2000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
Log.e("Request: ", "> " + url);
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
if (httpResponse != null) {
httpEntity = httpResponse.getEntity();
} else {
Log.e(TAG, "httpResponse is null");
}
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
And this is how I use the class:
nameValuePairs = new ArrayList<NameValuePair>();
String param_value = "value";
String param_name = "name";
nameValuePairs.add(new BasicNameValuePair(param_name, param_value));
// Creating service handler class instance
sh = new ServiceHandler();
String json = sh.makeServiceCall(Utils.getUrl, ServiceHandler.GET, nameValuePairs);
I am sending NameValuePair parameters to a php file on my server and this php file echoes one of three string values.
I need to write code in Java to send these parameters to the PHP file via POST and also save the php file's echo response to a String.
This is what I have so far:
public String getStringFromUrl(String url, List<NameValuePair> params) throws IOException {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
String response2 = (String) response;
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return response;
}
I know I have the right lines of code for sending the POST parameters but how do I read the value the php file echoes corresponding to the given POST parameters?
You can read the post response this way:
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
See the full example here:
http://www.mkyong.com/java/apache-httpclient-examples/
I can't parse Arabic/Persian text from SQL database. Everything is set to UTF-8. My SQL database text is set to utf8_general_ci. JSON parser is set to UTF-8 too.
Text is shown good in English. But when I use Arabic/Persian text in database, android shows text as ???????.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I have been r & d around a day and finally success to parse my arabic json response getting from server using following code.So, may be helpful to you.
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httppost = new HttpPost(Your_URL);
HttpResponse http_response= httpclient.execute(httppost);
HttpEntity entity = http_response.getEntity();
String jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.i("Response", jsonText);
Now, use jsonText for your further requirement.
Thank You
Maybe the problem is on server side. Check the raw String you got from the Server to see if it is correctly formatted.
I think it can help you by storing it as clob/blob, since once you have the bytes which were convereted from UTF-8 at server side, any client side code can also then using various String encoding formats to display the test.
Or my other advice, use a webview to display it, its more mature to handle these nuances.
I want to upload a txt file to a website, I'll admit I haven't looked into it in any great detail but I have looked at a few examples and would like more experienced opinions on whether I'm going in the right direction.
Here is what I have so far:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
private String ret;
HttpResponse response = null;
HttpPost httpPost = null;
public String postPage(String url, String data, boolean returnAddr) {
ret = null;
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
}
httpPost.setEntity(tmp);
try {
response = httpClient.execute(httpPost,localContext);
} catch (ClientProtocolException e) {
System.out.println("HTTPHelp : ClientProtocolException : "+e);
} catch (IOException e) {
System.out.println("HTTPHelp : IOException : "+e);
}
ret = response.getStatusLine().toString();
return ret;
}
And I call it as follows:
postPage("http://www.testwebsite.com", "data/data/com.testxmlpost.xml/files/logging.txt", true));
I want to be able to upload a file from the device to a website.
But when trying this way I get the following response back.
HTTP/1.1 405 Method Not Allowed
Am I trying the correct way or should I be doing it another way?
That code looks reasonable, the error is from the server and indicates that POST is not allowed for that page.
You're sending the literal string "data/data/com.testxmlpost.xml/files/logging.txt". If you want to post a file, use a FileEntity.