java - HTTP Request From Android Client
问题描述
I have a really basic spring boot application running on localhost and i'm trying to get some data from another app on android studio. My endpoint looks like this: http://localhost:8080/company/{id} and returns this:
In my android application, I have created a wrapper class:
package gr.games.panayiotis.myapplication;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Company {
@JsonProperty("id")
private long id;
@JsonProperty("name")
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And inside main application i'm creating a new class called Task that extends AsyncTask to get the api:
package gr.games.panayiotis.myapplication;
import android.os.AsyncTask;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
public class MainActivity extends AppCompatActivity {
public class Task extends AsyncTask<String, Void, ResponseEntity<Company>>{
@Override
protected ResponseEntity<Company> doInBackground(String... strings) {
String url = strings[0];
RestTemplate restTemplate = new RestTemplate();
try{
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
HttpEntity<String> entity = new HttpEntity<String>(headers);
int id = 1;
ResponseEntity<Company> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Company.class, id);
System.out.println(responseEntity.getStatusCode());
System.out.println(responseEntity.toString());
return responseEntity;
}catch (Exception e){
//System.out.println("ERROR:\n");
e.getMessage();
//System.out.println("\nEND OF ERROR");
return null;
}
}
protected void onPostExecute(ResponseEntity<Company> response){
//Company company = response.getBody();
// System.out.println(company.getName());
}
}
//A button invokes this method
public void getData(View view){
String url = "http://localhost:8080/company/1";
new Task().execute(url);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@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);
}
}
Inside the doInBackground() method my code runs up to the point where i call restTemplate.exchange(). After that it goes into the catch block and returns null to the response.
The first time i invoke my getData() method i get these warnings :
Capturing and displaying logcat messages from application. This behavior can be disabled in the
"Logcat output" section of the "Debugger" settings page.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/Java7Handlers: Unable to load JDK7 types (java.nio.file.Path): no Java7 type support added
I get no error but i can't figure out why i'm not getting a response. My Spring Boot application never gets a request. I just got into android so any help is much appreciated.
解决方案
经过一番挖掘,我发现了错误。
结果当你在模拟器上运行你的android应用程序时,localhost地址是这样的:http://10.0.2.2:8080
所以我所要做的就是改变我的url。
推荐阅读
- java - 休眠:如何使用带有逗号分隔内容的 varchar 列作为实体中的列表
- linux - 如何对多个子网使用条件?
- python - Tkinkter 没有正确接受国家代码
- php - 使用 is_numeric 时,switch case 没有选择正确的大小写
- flutter - 更新后文本溢出省略号中出现奇怪的字符
- scala - 由 2 个 O(1) 复杂度的列表组成的队列的 Scala 最大值
- javascript - 如何在 Javascript 的地图中访问 [set object}?
- excel - 从数字中识别文本的 Google 表格/Excel 公式
- amazon-web-services - 等待创建 EKS 节点组时出错:实例无法加入 kubernetes 集群
- python - 使用 python 脚本创建自动刷新 Tableau 仪表板