What can i do to use httpclient method in android studio. - android-studio

I am using HttpClient and defaultHttpClient Methods in getInternetData function on android studi. but these methods are no longer part of the SDK 23. how can i overcome this problem.i have used dependencies in build.gradle too , but still error remains here. Kindly tell me are there any other methods to call.?
public class GetMethodEx {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://api.twitter.com/1/statuses/public_timeline.json");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}

Related

How to show nearby locations from current location android studio?

I have been trying to display nearby locations from my current location. But when i run it and click the button to view the nearby locations nothing appears. The first time i ran it, it displayed but when i backed out and came back in, it didnt display anything. i tried cleaning the project and other methods.
this is the method in my main class:
public void findRestaurants(View v){
StringBuilder stringBuilder = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
stringBuilder.append("location="+latLngCurrent.latitude + "," +latLngCurrent.longitude);
stringBuilder.append("&radius="+5000);
stringBuilder.append("&keyword="+"restaurant");
stringBuilder.append("&key="+getResources().getString(R.string.google_map_keyy));
String url = stringBuilder.toString();
Object dataTransfer[] = new Object[2];
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlaces getnearbyPlaces = new getNearbyPlaces();
getnearbyPlaces.execute(dataTransfer);
}
public class getNearbyPlaces extends AsyncTask<Object,String,String> {
GoogleMap mMap;
String url;
InputStream is;
BufferedReader bufferedReader;
StringBuilder stringBuilder;
String data;
#Override
protected String doInBackground(Object... objects) {
mMap = (GoogleMap)objects[0];
url = (String)objects[1];
try {
URL myurl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) myurl.openConnection();
httpURLConnection.connect();
is = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
stringBuilder = new StringBuilder();
while((line = bufferedReader.readLine() ) != null){
stringBuilder.append(line);
}
data = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject parentObject = new JSONObject(s);
JSONArray resultsArray = parentObject.getJSONArray("results");
for (int i = 0; i<resultsArray.length(); i++){
JSONObject jsonObject = resultsArray.getJSONObject(i);
JSONObject locationObj = jsonObject.getJSONObject("geometry").getJSONObject("location");
String latitude = locationObj.getString("lat");
String longitude = locationObj.getString("lng");
JSONObject nameObject = resultsArray.getJSONObject(i);
String name_restaurant = nameObject.getString("name");
String vicinity = nameObject.getString("vicinity");
LatLng latLng = new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude));
MarkerOptions markeroptions = new MarkerOptions();
markeroptions.title(vicinity);
markeroptions.position(latLng);
mMap.addMarker(markeroptions);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
it worked the first time when i lunched it. Did i do something wrong?
hope you are doing fine. Can you replace the lines
new getNearbyPlaces().execute(dataTransfer);
instead of these 2 lines
getNearbyPlaces getnearbyPlaces = new getNearbyPlaces();
getnearbyPlaces.execute(dataTransfer);
I am not sure whether this is going to impact much, but this is the way AsyncTask class should be called.
If this is not working, can you share the entire code of this java page, so we can look at how findRestaurant() method is called.

AndroidStudio about HttpURLConnection

This is my method!
private String logInActivity() {
String userID = idText.getText().toString();
String userPW = pwText.getText().toString();
final String SERVER = "http://115.145.241.151:8080/AndroidCommunication/LoginActivity.jsp";
if (userID != null && userPW != null) {
final String QUERY = "?id=" + userID + "&pw=" + userPW;
HttpURLConnection connection = null;
URL url = null;
try {
url = new URL(SERVER+QUERY);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
return line;
} catch (Exception e) {
e.printStackTrace();
return "3";
}
} else {
Toast.makeText(GetReview.this, "Type all required info", Toast.LENGTH_SHORT).show();
return "2";
}
}
I'm just practicing HttpURLConnection( by GET METHOD). I know i shouldn't send passwords or ids like this way but i'm just practicing my exercise. But I just don't get why this goes to an Exception. Please help!
I didn't type my addresses or anything wrong because I tried it, and server was on. I debugged it and the connection.connect(); doesn't seems to work.
my onCreate goes:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_review);
pwText = findViewById(R.id.pwText);
idText = findViewById(R.id.idText);
resultText = findViewById(R.id.resultText);
findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginAsyncTask().execute(logInActivity());
}
});
}
The problem is that issuing HTTP requests on the main thread is not allowed by android. That's why you are receiving a NetworkOnMainThreadException exception. To resolve this, you can use an IntentService to do that job for you and then broadcast the results back to the receiver (your activity).
If you don't know much about android Services, then have a read in the documentation, you'll find yourself using them time and time again...
https://developer.android.com/guide/components/services#CreatingAService

getPostDataString(java.util.HashMap<java.lang.String,java.lang.String>) cannot be applied to (java.util.HashMap<java.lang.String,java.lang.String>[])

I'm trying to post to a server via Asynchronous Task and while converting Hashmap to String, this error occurred. What does that Error mean. Why does it occour ? How do I resolve this ?
here is my code:
public class NetworkAccess extends AsyncTask<HashMap<String,String>,Void,String> {
private URL url;
private HttpURLConnection con;
private OutputStream os;
#Override
protected String doInBackground(HashMap<String, String>... vals) {
String response = "";
try {
url = new URL("http://192.168.0.3/chow/user-login.php");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setConnectTimeout(1000);
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String pd = getPostDataString(vals); //Error
writer.write(pd);
writer.flush();
writer.close();
BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(bis));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
response = total.toString();
}
catch (Exception e){
e.printStackTrace();
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
The error which you got shows that you're directly trying to create a array of HashMap, rather you can create just Array of String, iterate the Collection and insert the HashMap objects into it.
Inside the getPostDataString(), change the code to
StringBuilder[] sb = new StringBuilder[100];
and check if it works.

send a JSON request with JSONObject as parameter?

I want to make an android-json request to a webservice with httpClient.
The method which i try to call is "authenticate"
The request should have the following structure:
{"id":"ID","method":"authenticate","params":{"user":"ANDROID",
"password":"PASSWORD", "client":"CLIENT"},"jsonrpc":"2.0"}
mandatory parameter: ?school=SCHOOLNAME
This is what i have tried:
class MyAsnycTask extends AsyncTask<String, String, String>{
protected String doInBackground(String... params) {
String apiUrl = "https://arche.webuntis.com/WebUntis/jsonrpc.do";
JSONObject jsonParams = new JSONObject();
JSONObject params1 = new JSONObject();
HttpClient client = new DefaultHttpClient();
// Prepare a request object
HttpPost post = new HttpPost(apiUrl);
post.setHeader("Content-type", "application/json");
try {
params1.put("?school","litec");
params1.put("user", "40146720133271");
params1.put("password", "1234567");
jsonParams.put("id", "ID");
jsonParams.put("method", "authenticate");
jsonParams.put("params", params1);
jsonParams.put("jsonrpc", "2.0");
StringEntity se = new StringEntity(jsonParams.toString());
post.setEntity(se);
} catch (JSONException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Execute the request
try {
HttpResponse response = client.execute(post);
Log.d("log_response: ", response.getStatusLine().toString());
// Get hold the response entity
HttpEntity entity = response.getEntity();
// if the response does not enclose the entity, there is no need
// to worry about it
if(entity != null){
// a simple JSON Response read
InputStream instream = entity.getContent();
String result;
// convert content of response to bufferedreader
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
instream.close();
}catch(IOException exp){
exp.printStackTrace();
}
}
result = sb.toString();
Log.d("Result of the Request: ", result);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "OK";
}
protected String doInBackground(String result) {
return result;
// TODO Auto-generated method stub
}
}
After executing this, i get the request:
{"jsonrpc":"2.0","id":"error","error":{"message":"invalid schoolname","code":-8500}}
So its telling me that our schoolname is false.
So what can i do, is my way to pass parameters wrong ?
I saw your question some time ago, but I was not able to answer. I'm working with the WebUntis API as well, and I dont know if you solved the error, but it is a simple error in the url. As mentionend in the API, the mandatory paramter for the method 'authenthicate' is ?school=SCHULNAME. Your Url in the code is 'https://arche.webuntis.com/WebUntis/jsonrpc.do', but the mandatory parameter SCHULNAME is not given. Your Url should look like this: https://arche.webuntis.com/WebUntis/jsonrpc.do?school=SCHULNAME. Maybe you have to add the length of your request. E.g. if you use the method authenthicate: {"id":"ID","method":"authenticate","params":{"user":"USR", "password":"PW", "client":"MyApp"},"jsonrpc":"2.0"}
In this case length would be 109. I hope this helped, even if the question is over a month old. For other Googlers: If you are not using an AsyncTask, you have to return true, not ok.
EDIT:
The code looks like this (I haven't tested this yet, I hope it works):
class MyAsnycTask extends AsyncTask<String, String, String>{
protected String doInBackground(String... params) {
String apiUrl = "https://arche.webuntis.com/WebUntis/jsonrpc.do?school=SCHULNAME"; //Changes here
JSONObject jsonParams = new JSONObject();
JSONObject params1 = new JSONObject();
HttpClient client = new DefaultHttpClient();
// Prepare a request object
HttpPost post = new HttpPost(apiUrl);
post.setHeader("Content-type", "application/json");
try {
params1.put("user", "40146720133271");
params1.put("password", "1234567");
params1.put("client", "seriouslysAndroidApp"); //You can change the name
jsonParams.put("id", "ID");
jsonParams.put("method", "authenticate");
jsonParams.put("params", params1);
jsonParams.put("jsonrpc", "2.0");
StringEntity se = new StringEntity(jsonParams.toString());
post.setHeader("Content-length",""+se.getContentLength()); //header has to be set after jsonparams are complete
post.setEntity(se);
} catch (JSONException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Execute the request
try {
HttpResponse response = client.execute(post);
Log.d("log_response: ", response.getStatusLine().toString());
// Get hold the response entity
HttpEntity entity = response.getEntity();
// if the response does not enclose the entity, there is no need
// to worry about it
if(entity != null){
// a simple JSON Response read
InputStream instream = entity.getContent();
String result;
// convert content of response to bufferedreader
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
instream.close();
}catch(IOException exp){
exp.printStackTrace();
}
}
result = sb.toString();
Log.d("Result of the Request: ", result);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "OK";
}
protected String doInBackground(String result) {
return result;
// TODO Auto-generated method stub
}

how to mock final method of super class

I would like mock DefaultHttpClient.java and execute method in AbstractHttpClient.java, DefaultHttpClient extends AbstractHttpClient java class, and execute method is final method, so i need to powermock to mock final method.
#RunWith(PowerMockRunner.class)
#PrepareForTest(DefaultHttpClient.class)
//#PrepareForTest(AbstractHttpClient.class)
public class RestClientTest {
DefaultHttpClient client;
RestClient restClient = new RestClient();
#Test
public void getAll() throws Exception{
client = PowerMockito.spy(new DefaultHttpClient());
//PowerMockito.mock(DefaultHttpClient.class);
//Mockito.mock(DefaultHttpClient.class);
HttpResponse response = PowerMockito.mock(HttpResponse.class);
MarketplaceTO sampleData = new MarketplaceTO();
sampleData.setName("name");
//String endpoint = "";
//ProtocolVersion protoCol = new ProtocolVersion("HTTP", 2, 1);
//StatusLine status = new BasicStatusLine(protoCol, HttpStatus.SC_OK, null);
//HttpResponse response = new BasicHttpResponse(status);
BasicHttpEntity entity = new BasicHttpEntity();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(sampleData);
oos.flush();
oos.close();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
entity.setContent(is);
entity.setContentLength(is.available());
response.setEntity(entity);
//PowerMockito.doNothing().when((AbstractHttpClient)client).execute(Mockito.any(HttpUriRequest.class),Mockito.any(HttpContext.class));
PowerMockito.doReturn(response).when(client).execute(Mockito.any(HttpUriRequest.class));
//HttpGet getRequest = new HttpGet(endpoint);
//PowerMockito.when(client.execute(Mockito.any(HttpGet.class))).thenReturn(response);
//Mockito.stub(client.execute(getRequest)).toReturn(response);
//System.out.println("code "+response.getStatusLine().getStatusCode());
EMResponse<MarketplaceTO> responseData = restClient.getAll("", MarketplaceTO.class);
//System.out.println("name is "+responseData.getModelObject().getName());
Assert.assertEquals("name", responseData.getModelObject().getName());
}
}
and RestClient.java has
public <T> EMResponse<T> getAll(String entity, Class<T> entityClass) {
StringBuffer bufferedReader = null;
String output = "";
EMResponse<T> emResponse = null;
EMError emError = null;
ObjectMapper objectMapper = new ObjectMapper();
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
bufferedReader = new StringBuffer();
String endpoint = /*EntityManagerProperties
.get(EntityManagerProperties.ENTITY_MANAGER_SERVICE_URL)
+ "/" + entity*/"http://google.com/abcd";
HttpGet getRequest = new HttpGet(endpoint);
HttpResponse response = httpClient.execute(getRequest);
System.out.println("code "+response.getStatusLine().getStatusCode());
return getEntityObjects(response, entityClass, true);
} catch (ClientProtocolException e) {
logger.error("Exception", e);
} catch (IOException e) {
logger.error("Exception", e);
} finally {
//httpClient.getConnectionManager().shutdown();
}
return emResponse;
}
if i call after mocking execute method, then also it is calling actual method.
Please help me. sorry for my english.
Reason why its calling original execute method is because you have used a constructor
DefaultHttpClient httpClient = new DefaultHttpClient();
in RestClient.java class.
so you should must mock the constructor and return your mocked object
Add this line
whenNew(DefaultHttpClient.class).withNoArguments().thenReturn(client);
before using:
PowerMockito.doReturn(response).when(client)
.execute(Mockito.any(HttpUriRequest.class));
and
Change #PrepareForTest(DefaultHttpClient.class) to #PrepareForTest({DefaultHttpClient.class, RestClient.class})
This will solve your problem.

Resources