我要做的就是下载一些JSON并将其反序列化为一个对象.我还没有下载JSON.
我能找到的几乎所有HttpClient示例,包括apache站点上的那些看起来都像......
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
public void blah() {
HttpClient client = new DefaultHttpClient();
...
}
Run Code Online (Sandbox Code Playgroud)
但是,Netbeans告诉我,这DefaultHttpClient
已被弃用.我已经尝试使用谷歌搜索DefaultHttpClient deprecated
和其他许多变化,我无法找到任何有用的结果,所以我显然错过了一些东西.
下载网页内容的正确Java7方式是什么?作为语言的一部分,真的没有像样的Http客户端吗?我觉得很难相信.
我对Maven的依赖是......
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>LATEST</version>
<type>jar</type>
</dependency>
Run Code Online (Sandbox Code Playgroud) 出于测试/基准测试的目的,我想编写一个Java程序,它在循环中执行以下任务:
此循环同时在多个线程上运行.
启动后,程序可以在短时间内正常运行,并且每个线程每秒可以执行约300个周期(网络服务器在同一台机器上运行).但是在5-7秒后,我得到了BindException: Address already in use
.
在20-30秒的冷却时间后重新启动程序会导致相同的行为; 当我立即重启它而不等待时,它会立即崩溃...所以我认为这可能是绑定资源的问题.
这是一种快速而肮脏的方法HttpURLConnection
.相关部分:
从Web服务器获取数据
public String fetchData() throws IOException {
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setUseCaches(false);
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
conn.disconnect();
return response.toString();
}
Run Code Online (Sandbox Code Playgroud)
发送答案
public void sendData(byte[] data) throws IOException {
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream(); …
Run Code Online (Sandbox Code Playgroud) 我试图找出从 Spark 调用 Rest 端点的最佳方法。
我目前的方法(解决方案 [1])看起来像这样 -
val df = ... // some dataframe
val repartitionedDf = df.repartition(numberPartitions)
lazy val restEndPoint = new restEndPointCaller() // lazy evaluation of the object which creates the connection to REST. lazy vals are also initialized once per JVM (executor)
val enrichedDf = repartitionedDf
.map(rec => restEndPoint.getResponse(rec)) // calls the rest endpoint for every record
.toDF
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用 .mapPartitions() 而不是 .map(),但是查看 DAG,看起来 spark 优化了重新分区 -> 无论如何映射到 mapPartition。
在第二种方法(解决方案 [2])中,为每个分区创建一次连接,并为分区内的所有记录重用。
val newDs = myDs.mapPartitions(partition => { …
Run Code Online (Sandbox Code Playgroud)