Requesting the POST API of personality insights from Android - android

I am trying to invoke the POST API of personality insights from Android on a button click and display the response on the screen after proper parsing. The API details of the personality insights are here.
When I tried to test this using POSTMAN I am getting the correct response. But when I try to invoke this from Android, the logcat is not showing any error and the application doesn't terminate in the emulator. The initial invocation of API is not working for me.
I referred this link for the android code
This is the code which I used. Please let me know of any mistakes that I have made.
Edited :
I also tried this example link but everything seems to be deprecated for my current android API versions.
HTTP Example.java
package com.example.httpexample;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView, button;
TextView textView1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView1);
button = (TextView)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener(){
// When user clicks button, calls AsyncTask.
// Before attempting to fetch the URL, makes sure that there is a network connection.
#Override
public void onClick(View v) {
String stringUrl = "https://gateway.watsonplatform.net/personality-insights/api/v2/profile" (https://gateway.watsonplatform.net/personality-insights/api/v2/profile%27);
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadWebpageTask().execute(stringUrl);
} else {
textView.setText("No network connection available.");
}
}
});
}
public TextView getTextView()
{
TextView txtView = (TextView)findViewById(R.id.textView2);
return txtView;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
DownloadWebpageTask.java
package com.example.httpexample;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;
class DownloadWebpageTask extends AsyncTask<String, Void, String> {
private static final String DEBUG_TAG = "HttpExample";
#Override
protected String doInBackground(String... urls) {
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String downloadUrl(String myurl) throws IOException, JSONException{
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//conn.setRequestMethod("GET");
final String basicAuth = "Basic " + Base64.encodeToString(""username":password".getBytes(), Base64.NO_WRAP);
conn.setRequestProperty ("Authorization", basicAuth);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
System.out.println("first connection");
JSONObject contentItems = new JSONObject();
contentItems.put("id", "");
contentItems.put("userid", "");
contentItems.put("created", "int");
contentItems.put("updated", "int");
contentItems.put("contenttype", "");
contentItems.put("charset", "");
contentItems.put("language", "int");
contentItems.put("content", "Hi. This is the sample input");
contentItems.put("parentid", "");
contentItems.put("reply", false);
contentItems.put("forward", false);
System.out.println("connection done");
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
System.out.println("Content " + contentAsString);
MainActivity obj = new MainActivity() ;
TextView tv = obj.getTextView();
tv.setText(contentAsString + response);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}

It does not seem you are sending your contentItems object anywhere - you populate it, but never include it as payload in the request.
In addition, this contentItems is just one item object you need to include in the JSON input. The JSON input should look like:
{ "contentItems": [ <item1>, <item2> ] }
and you are just creating something that fits as one of the items above.
If you are passing some simple input to the API, I would suggest you include the header Content-Type: text/plain and forget about JSON formatting for the moment, as it is going to be simpler.

Related

How do i send post request to a webservice?

I follow this post http://hmkcode.com/android-send-json-data-to-server/ and some functions is depreciated. I like to understand how I send an information to a web service.
I try to update the post but i got some mistake.. I know my code has some mistake My code is:
enter code here
package com.example.paulo.myapp.POST;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.paulo.myapp.R;
import com.facebook.internal.BundleJSONConverter;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Post_Dados extends AppCompatActivity implements View.OnClickListener {
TextView isconected;
EditText customer, pais, twitter;
Button btn_enviar;
String person, country, tw;
static Dados dados;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post__dados);
/* recupera as views */
isconected = (TextView) findViewById(R.id.conected);
customer = (EditText) findViewById(R.id.customer);
pais = (EditText) findViewById(R.id.pais);
twitter = (EditText) findViewById(R.id.twitter);
btn_enviar = (Button) findViewById(R.id.sendWS);
/* checa se está conectado */
if (isConnected()) {
isconected.setText("Conectado !!!!");
}
else {
isconected.setText("Não conectado!!!");
}
/* click do botão */
btn_enviar.setOnClickListener(this);
}
private boolean isConnected() {
ConnectivityManager cm = (ConnectivityManager ) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if ( info != null && info.isConnected()){
return true;
}
else { return false; } }
#Override
public void onClick(View view) {
String c = customer.getText().toString();
String p = pais.getText().toString();
String t = twitter.getText().toString();
if ( c.equals("") || p.equals("") || t.equals("") )
{
Toast.makeText(getBaseContext(), "Preenche os campos os dados!", Toast.LENGTH_LONG).show();
}
else{
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
}
}
/*metodo de conexao */
private static String POST(String url, String person) throws IOException, JSONException {
InputStream inputStream = null;
String result = "";
try{
/* 1. cria o httpClient */
URL endWeb = new URL(url);
HttpURLConnection con = (HttpURLConnection) endWeb.openConnection();
// 2. configurando o POST
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setUseCaches(false);
con.setRequestProperty("Accept", "application/json");
//3. define enviar e receber
con.setDoOutput(true);
con.setDoInput(true);
//4.faz a conexao
con.connect();
//5. Objeto json
String json = " ";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name",dados.getNome());
jsonObject.accumulate("country", dados.getEmail());
jsonObject.accumulate("twitter", dados.getTwitter());
//6.connverte json to json string
json = jsonObject.toString();
// Escreve o objeto JSON usando o OutputStream da requisição:
OutputStream outputStream = con.getOutputStream();
outputStream.write(json.getBytes("UTF-8"));
}
catch (Exception e){
throw e;
}
return "ok";
}
private class HttpAsyncTask extends AsyncTask<String, Void, String>{
String result;
#Override
protected String doInBackground(String... urls) {
dados = new Dados(person.toString(), country.toString(), tw.toString());
try {
result = POST(urls[0], person);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Dados enviados!", Toast.LENGTH_LONG).show();
}
}
}
I this url http://hmkcode.appspot.com/post-json/index.html is to check it´s ok.
I like a help to get it ok.
Unfortunately sending HTTP requests in Android is quite the pain without using 3rd party libraries. Fortunately retrofit is awesome and is very widely used. There are a lot tutorials for it, you might try this one for example.

Performing different operations in Thread - android

I've this condition to write the server call that executes every 50ms.
The server call must be from volley.
But the difficulty i am facing is every server call has different urls and how to pass these different urls in thread so to call server every 50ms.?
I am not an expert in android, but this is what I could think of if you want to call different urls after 50ms. Please correct me if I am wrong :)
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
int i=0;
final String[] urlArray = new String[]{"http://google.com","http://fb.com"};//your url array here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Runnable task = new Runnable() {
public void run() {
String currentURL= MainActivity.this.getNextURL();
new HitWebService().execute(currentURL);
}
};
worker.schedule(task, 50, TimeUnit.SECONDS);
}
private String getNextURL(){
String currentURL= urlArray[i];
if(i == urlArray.length){
i=0;
}
else{
i++;
}
return currentURL;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class HitWebService extends AsyncTask<String,Void,String> {
protected void onPreExecute(){
//do whatever you want with respect to ui
}
#Override
protected String doInBackground(String... params){
HttpURLConnection connection=null;
String stringUrl= params[0];
try {
URL url= new URL(stringUrl);
connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream outputStream=new DataOutputStream(connection.getOutputStream());
String parameters = "initialise your parameters here, pass parameters also in params and access it like params[1]";
outputStream.writeBytes(parameters);
outputStream.flush();
outputStream.close();
InputStream inputStream=connection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
StringBuffer response = new StringBuffer();
String line;
while((line=bufferedReader.readLine())!=null){
response.append(line);
}
bufferedReader.close();
return response.toString();
}
catch (MalformedURLException malformedException){
return malformedException.toString();
}
catch (IOException ioException){
return ioException.toString();
}
finally {
if(connection !=null){
connection.disconnect();
}
}
}
#Override
protected void onPostExecute(String response){
//do whatever you want here
}
}
}

How to read the web contents with android?

I have a method that should actually read the data from the web and returns the content as a String, but it is not working.I would be glad if you can help me out! I don't know where I screwed up. I added the INTERNET uses permission in the manifest file but doesn't work. Well, I tested on the emulator only.
public String getInternetData() throws Exception {
BufferedReader in = null;// read info
String response = null;
try {
HttpClient client = new DefaultHttpClient(); // default client
// process application to handle data from web
URI website = new URI("https://www.random.com");
// get information from web
HttpGet request = new HttpGet(); // get data
InputStream inputStream = null;
request.setURI(website);// connected and request
// respons
HttpResponse httpResponse = client.execute(request);
int statutCode = httpResponse.getStatusLine().getStatusCode();
int length = (int) httpResponse.getEntity().getContentLength();
inputStream = httpResponse.getEntity().getContent();
Reader reader = new InputStreamReader(inputStream, "UTF-8");
int inChar;
StringBuffer stringBuffer = new StringBuffer();
while ((inChar = reader.read()) != -1) {
stringBuffer.append((char) inChar);
}
response = stringBuffer.toString();
} finally {
}
return response;
}
I checked your code and it's working. I'm not sure if you are establishing a connection on your EDT or not but here's a template that's working with your code. Btw your link doesn't have a SSL, you need to connect to http.
package com.example.stackover;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
(new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
getInternetData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}).execute();
return rootView;
}
public void getInternetData() throws Exception {
BufferedReader in = null;// read info
String response = null;
try {
HttpClient client = new DefaultHttpClient(); // default client
// process application to handle data from web
URI website = new URI("http://www.random.com");
// get information from web
HttpGet request = new HttpGet(); // get data
InputStream inputStream = null;
request.setURI(website);// connected and request
// respons
HttpResponse httpResponse = client.execute(request);
int statutCode = httpResponse.getStatusLine().getStatusCode();
int length = (int) httpResponse.getEntity().getContentLength();
inputStream = httpResponse.getEntity().getContent();
Reader reader = new InputStreamReader(inputStream, "UTF-8");
int inChar;
StringBuffer stringBuffer = new StringBuffer();
while ((inChar = reader.read()) != -1) {
stringBuffer.append((char) inChar);
}
response = stringBuffer.toString();
} finally {
}
Log.v("Information", response);
}
}
}

Getting json type mismatch error

I am new to android development and am trying to work with json data. I followed the web page "
http://hmkcode.com/android-parsing-json-data/" to make a simple app to get and display json. It works fine with the tutorial json web site. But when I change the url to point to my website I get an exception error on the line "JSONObject json = new JSONObject(result);"
03-15 08:56:10.518: W/System.err(1330): org.json.JSONException: Value <?xml of type
java.lang.String cannot be converted to JSONObject
03-15 08:56:10.528: W/System.err(1330): at org.json.JSON.typeMismatch(JSON.java:111)
03-15 08:56:10.528: W/System.err(1330): at org.json.JSONObject.<init>(JSONObject.java:159)
03-15 08:56:10.528: W/System.err(1330): at org.json.JSONObject.<init>(JSONObject.java:172)
When I display the string I get it looks like this (almost, I had trouble formatting, the mgmtresponse line is all one line, I also blocked out the ip address):
<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<mgmtResponse
responseType="operation"requestUrl="https://128.205.x.xxx/webacs/api/v1/op/info/version"
rootUrl="https://128.205.x.xx/webacs/api/v1/op">
-<versionInfoDTO>
<result>2.0.0.0.294</result>
</versionInfoDTO>
</mgmtResponse>
Here is the main section of code. As you can see I tried a bunch of things and commented out a bunch of things to get down to the problem. I am stuck at the point where I can not take my input and convert it to a json object. I think I need to format the response some how but I just can not figure out what is wrong.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Base64;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText etResponse;
TextView tvIsConnected;
static TextView response_code;
static String httpcode;
static String version;
#Override
// oncreate is called when activity is created
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
etResponse = (EditText) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
response_code = (TextView) findViewById(R.id.response_code);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("network is connected");
}
else{
tvIsConnected.setText("network is NOT connected");
}
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("https://128.205.x.xx/webacs/api/v1/op/info/version");
// new HttpAsyncTask().execute("https://hmkcode.appspot.com/rest/controller/get.json");
}
public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new MyHttpClient();
HttpGet request = new HttpGet(url);
request.setHeader("Authorization", "Basic " + Base64.encodeToString
("username:password".getBytes(), Base64.NO_WRAP));
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(request);
final int StatusCode = httpResponse.getStatusLine().getStatusCode();
String st=String.valueOf(StatusCode);
httpcode = st;
//HttpResponse httpResponse = HttpClient.execute(new HttpGet(url));
// receive response as inputStream
//HttpEntity entity = httpResponse.getEntity();
//result = EntityUtils.toString(entity);
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader
(inputStream,"iso-8859-1"),8);
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line+"\n";
inputStream.close();
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService
(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
// displays results to Edittext and displays recieved to toast
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
response_code.setText(httpcode);
try {
//etResponse.setText(result);
JSONObject json = new JSONObject(result);
//etResponse.setText(json.toString(1));
//JSONObject mgmtResponse =
// new JSONObject(json.getString("mgmtResponse"));
//JSONObject versionInfoDTO =
// new JSONObject(mgmtResponse.getString("versionInfoDTO"));
version = "NCS-Version";
//
//JSONArray articles = json.getJSONArray("articleList"); //get articles array
//str += "articles length = "+json.getJSONArray("articleList").length();
//str += "\n--------\n";
//str += "names: "+articles.getJSONObject(0).names(); //get first articles keys
//str += "\n--------\n";
//str += "url: "+articles.getJSONObject(0).getString("url"); //return an article url
//String str = "NCS Version";
//version += versionInfoDTO.getJSONObject("result");
etResponse.setText(version);
// not - etResponse.setText(json.toString(1));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//etResponse.setText(version);
}
}
}
As Rashmi points out, you are receiving data in XML-format, and attempting to parse it as JSON-format, which is giving you an error. The format of the data can usually be specified in the request URL.
EDIT
Your are using the URL https://128.205.x.xx/webacs/api/v1/op/info/version and I don't know what that is, if it's your own server or not, but usually, APIs provide both XML and JSON formats, which could look something like this:
https://example.com:2087/xml-api/functionname
for XML and
https://example.com:2087/json-api/functionname
for JSON
Some webservices will allow/require you to specify "application/json" as the accept header, so in addition to this:
HttpGet request = new HttpGet(url);
request.setHeader("Authorization", "Basic " + Base64.encodeToString
("username:password".getBytes(), Base64.NO_WRAP));
Say what you want back:
request.setHeader("Accept", "application/json");
And, if required, what you are supplying:
request.setHeader("Content-type", "application/json");

java.net.socketException:operation time out when running app on real device

this code works fine on emulator, but on real device it gives
java.net.SocketException:the operation timed out
ive got a php script running on my xampp server.
package com.example.new1;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tx;
StringBuilder stringBuilder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tx= (TextView)findViewById(R.id.text);
}
public void func(View view)
{
//tx.setText("Working fine till here.");
new FetchSQL().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class FetchSQL extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... arg0) {
URL url = null;
BufferedReader reader = null;
String myUrl = "http://10.22.35.4:80/conc2.php";
try
{ url =new URL(myUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15*10000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
// TODO Auto-generated method stub
return stringBuilder.toString();
}
catch(final Exception e)
{
return e.toString();
}
}
protected void onPostExecute(final String result)
{
tx.setText(result);
}
}
}
when i click on button it takes the amt of time ive set in my code, and then fails giving me the error in my textview. please help
my php code.
<?php
// attempt a connection
$dbh = pg_connect("host=10.22.35.11 dbname=iwmp_dev2 user=postgres ");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
//$sql = $_POST['pLat'];
$sql = "SELECT officer_name FROM iwmp_officer";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
$array = array();
// iterate over result set
// print each row
while ($row = pg_fetch_assoc($result, null)) {
$i++;
$array = implode('+',$row);
echo $array;
}
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
?>
java.net.SocketException exception comes when the port that you are trying to reach is not closed or not available. It takes the amount of time you have specified for searching the port and then gets out.
Firstly, try to call this service on your mobile web browser to check whether it is available or not. If it does not show that means your device is not connected to the network on which this file resides.
It may be possible that your firewall is not allowing to ping your port. When you are doing with your emulator it works since its on same PC but in case of your real device it connects via local network and some time Firewall does not allow. Solution: unblock this request on firewall or try this by closing your firewall.

Categories

Resources